package com.tensquare.friend.interceptor;

import com.tensquare.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        final String authorization = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(authorization)) {
            if (authorization.startsWith("Bearer ")) {
                try {
                    final String token = authorization.substring(7);
                    Claims claims = jwtUtil.parseJWT(token);
                    if (!StringUtils.isEmpty(claims)) {
                        if ("admin".equals(claims.get("roles"))) {
                            request.setAttribute("Authorization_ADMIN", claims);
                        } else if ("user".equals(claims.get("roles"))) {
                            request.setAttribute("Authorization_USER", claims);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("请重新登录认证");
                }
            }
        }
        return true;
    }
}
